package Rtype;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.Timer;


public class Game extends JPanel implements ActionListener {

    private Timer timer;
    private Ship ship;

    public Game() {

        addKeyListener(new TAdapter());
        setFocusable(true);
        setBackground(Color.BLACK);
        setDoubleBuffered(true);

        ship = new Ship();

        timer = new Timer(5, this);
        timer.start();
    }


    public void paint(Graphics g) {
        super.paint(g);

        Graphics2D g2d = (Graphics2D)g;
        g2d.drawImage(ship.getImage(), ship.getX(), ship.getY(), this);

        ArrayList<Shot> ms = ship.getMissiles();
        
        int length = ms.size();
        for (int i = 0; i < length; i++) {
			Shot s = (Shot) ms.get(i);
			g2d.drawImage(s.getImage(),s.getX(),s.getY(),this);
		}
        
       Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }


    public void actionPerformed(ActionEvent e) {
    	ArrayList<Shot> ms=ship.getMissiles();
    	
    	int length=ms.size();
    	for (int i = 0; i < length; i++) {
			Shot s = (Shot) ms.get(i);
			if(s.visible)
				s.move();
			else
				ms.remove(i);
		}
    	
    	ship.move();
        repaint();  
    }


    private class TAdapter extends KeyAdapter {

        public void keyReleased(KeyEvent e) {
            ship.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            ship.keyPressed(e);
        }
    }

}